<template>
  <el-dialog class="gl_dialog_TitleLine" :title="$t('messageCenter.write')" :visible.sync="isShowWrite" :before-close="goBack" :close-on-click-modal="false" width="880px">
    <el-form ref="DraftCreateDto" :model="DraftCreateDto" :rules="DraftCreateDto_Rules" label-width="120px" class="form gl_form_mini">
      <el-form-item :label="$t('messageCenter.title')" prop="title">
        <el-input v-model="DraftCreateDto.title" :placeholder="$t('messageCenter.placeholderTitle')" class="item" size="mini" clearable />
      </el-form-item>
      <el-form-item :label="$t('messageCenter.addressee')" prop="targetIdList">
        <!-- <el-cascader v-model="DraftCreateDto.targetIdList" placeholder="请选择收件人" class="item" :options="options" :props="props" size="mini" @visible-change="isshowPop" /> -->
        <el-select v-model="DraftCreateDto.targetIdList" :placeholder="$t('messageCenter.placeholderAddressee')" multiple class="item" size="mini" popper-class="select_down" value-key="id" @change="changeSelect" @visible-change="isshowPop">
          <div style="float: left; width:50%; height:100%; border-right: 1px solid #dfe4ed; min-height:200px">
            <el-tree :data="treeData" node-key="id" :props="defaultProps" @node-click="handleNodeClick" />
          </div>
          <div v-loading="loading" style="float: right; height:100%">
            <el-option :disabled="true" value="" style="display: none" />
            <el-input v-model="search" style="width:44%; margin-left:20px" size="mini" />
            <el-checkbox v-model="checked" style="margin:10px 20px" @change="selectAll">{{ $t('messageCenter.all') }}</el-checkbox>
            <el-option v-for="item in searchOptions" :key="item.id" :label="item.name" :value="item.id" class="option">
              <div style="float: right; width:100%; color: #8492a6;">{{ item.name }}</div>
            </el-option>
          </div>
        </el-select>
        <div v-if="showPop" class="cascader" />
      </el-form-item>
      <el-form-item :label="$t('messageCenter.noticeContent')" prop="message">
        <!-- <Tinymce id="tinymce" v-model="ruleForm.text" :height="300" /> -->
        <Tinymce v-if="isShowWrite" v-model="DraftCreateDto.message" :height="300" />
      </el-form-item>
    </el-form>
    <span slot="footer">
      <el-button size="mini" @click="goBack">{{ $t('button.cancel') }}</el-button>
      <el-button :loading="draftLoading" type="primary" size="mini" @click="addDraft('DraftCreateDto')">{{ $t('button.addDraft') }}</el-button>
      <el-button :loading="sendLoading" type="primary" size="mini" @click="sendOut('DraftCreateDto')">{{ $t('button.send') }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { translateByCode } from '@/lib/getTransData';
import { DraftCreateDto, SendMessageInput, DraftUpdateDto } from '@/lib/form/swaggerForm';
import { DraftCreateDto_Rules } from '@/lib/validate/writeMessage/index.js';
import { api_GET_OrganizationUnitsTree, api_GET_OrganizationUnitsIdUsers } from '@/extend/api/swaggerApi/identity.js';
import { api_POST_Draft, api_PUT_Draft, api_POST_MessageSendMessage } from '@/extend/api/swaggerApi/chat.js';
import Tinymce from '@/components/Tinymce';
export default {
  name: 'Write',
  components: { Tinymce }, // 富文本编辑器
  props: {
    isWrite: { // 控制弹出框的显示
      type: Boolean,
      default: false
    },
    edit: { // 是否是编辑
      type: Boolean,
      default: false
    },
    rowData: { // 通知草稿
      type: [Object, Array],
      default: () => {}
    }
  },
  data() {
    return {
      loading: false,
      sendLoading: false,
      draftLoading: false,
      isShowWrite: this.isWrite,
      DraftCreateDto: new DraftCreateDto(),
      SendMessageInput: new SendMessageInput(),
      DraftUpdateDto: new DraftUpdateDto(),
      DraftCreateDto_Rules: new DraftCreateDto_Rules(),
      showPop: false,
      props: { multiple: true }, // 多选
      options: [],
      treeData: [], // 组织机构树
      defaultProps: {
        children: 'children',
        label: 'displayName'
      },
      checked: false,
      search: '' // 全选
    };
  },
  computed: {
    // 搜索
    searchOptions () {
      const search = this.search;
      if (search) {
        return this.options.filter(data => {
          return Object.keys(data).some(key => {
            return String(data[key]).toLowerCase().indexOf(search) > -1;
          });
        });
      }
      return this.options;
    }
  },
  watch: {
    isWrite(val) {
      this.isShowWrite = val; // 控制弹出框的显示
      if (val === true) {
        this.isEdit();
      }
      if (this.$refs.DraftCreateDto) {
        this.$refs.DraftCreateDto.clearValidate('message');
      }
    },
    'DraftCreateDto.message': {
      handler(newval) {
        if (this.$refs.DraftCreateDto && newval.message !== '') {
          this.$refs.DraftCreateDto.validateField('message');
        }
      }
    }
  },
  created() {
    this.api_GET_OrganizationUnitsTree();
  },
  methods: {
    // 获取组织机构树
    api_GET_OrganizationUnitsTree() {
      const data = {
        includeDetails: true
      };
      this.loading = true;
      api_GET_OrganizationUnitsTree(data).then(res => {
        this.treeData = res.items;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    // 通知草稿
    isEdit() {
      if (this.edit) {
        this.DraftCreateDto.title = this.rowData.title;
        this.DraftCreateDto.targetIdList = this.rowData.targetUsers.map(item => {
          return item.userId;
        });
        this.options = this.rowData.targetUsers.map(item => ({
          id: item.userId,
          name: item.name
        }));
        this.DraftCreateDto.message = this.rowData.message;
      }
    },
    isshowPop(val) {
      if (val) {
        this.showPop = true;
      } else {
        this.showPop = false;
        this.$refs.DraftCreateDto.validateField('targetIdList');
      }
    },
    // 取消
    goBack() {
      this.isShowWrite = false;
      this.$emit('showWrite', false);
      this.$refs.DraftCreateDto.resetFields();
      this.checked = false;
    },
    // 发送
    sendOut(formName) {
      const that = this;
      this.sendLoading = true;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          that.SendMessageInput = that.DraftCreateDto;
          that.SendMessageInput.targetUserIds = that.DraftCreateDto.targetIdList;
          if (this.edit) {
            that.SendMessageInput.draftId = this.rowData.id;
          } else {
            that.SendMessageInput.draftId = null;
          }
          api_POST_MessageSendMessage(that.SendMessageInput).then(res => {
            this.sendLoading = false;
            this.isShowWrite = false;
            this.$emit('showWrite', false);
            this.$refs.DraftCreateDto.resetFields();
            this.checked = false;
            this.$message({
              type: 'success',
              message: translateByCode('alert.send')
            });
            this.$parent.refreshList();
          }).catch(() => {
            this.sendLoading = false;
          });
        } else {
          return false;
        }
      });
    },
    // 加入草稿箱 or 更新草稿
    addDraft(formName) {
      this.draftLoading = true;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.edit) {
            this.DraftUpdateDto = this.DraftCreateDto;
            this.DraftUpdateDto.draftId = this.rowData.id;
            api_PUT_Draft(this.DraftUpdateDto).then(res => {
              this.draftLoading = false;
              this.isShowWrite = false;
              this.$refs.DraftCreateDto.resetFields();
              this.checked = false;
              this.$emit('showWrite', false);
              this.$message({
                type: 'success',
                message: translateByCode('alert.update')
              });
              this.$parent.refreshList();
            }).catch(() => {
              this.draftLoading = false;
            });
          } else {
            api_POST_Draft(this.DraftCreateDto).then(res => {
              this.draftLoading = false;
              this.isShowWrite = false;
              this.$refs.DraftCreateDto.resetFields();
              this.checked = false;
              this.$emit('showWrite', false);
              this.$message({
                type: 'success',
                message: translateByCode('alert.draft')
              });
            }).catch(() => {
              this.draftLoading = false;
            });
          }
        } else {
          return false;
        }
      });
    },
    // 全选
    selectAll() {
      if (this.checked) {
        // 全选
        this.searchOptions.map((item) => {
          this.DraftCreateDto.targetIdList.push(item.id);
          this.DraftCreateDto.targetIdList = Array.from(new Set(this.DraftCreateDto.targetIdList));
        });
      } else {
        // 全不选
        let idList = [];
        if (this.searchOptions.length > 0) {
          idList = this.searchOptions.map(item => {
            return item.id;
          });
        }
        // 去掉两个数组的相同值
        const tempArray1 = [];
        const tempArray2 = [];
        for (let i = 0; i < idList.length; i++) {
          tempArray1[idList[i]] = true;
        }
        for (let i = 0; i < this.DraftCreateDto.targetIdList.length; i++) {
          if (!tempArray1[this.DraftCreateDto.targetIdList[i]]) {
            tempArray2.push(this.DraftCreateDto.targetIdList[i]);
          }
        }
        this.DraftCreateDto.targetIdList = tempArray2;
      }
    },
    changeSelect(val) {
      let idList = [];
      if (this.searchOptions.length > 0) {
        idList = this.searchOptions.map(item => {
          return item.id;
        });
      }
      const tf = this.includes(val, idList);
      // 包含全部，全选变为true
      if (tf) {
        this.checked = true;
      } else {
        this.checked = false;
      }
    },
    // 是否包含
    includes(arr1, arr2) {
      return arr2.every(val => arr1.includes(val));
    },
    // 获得相应组织机构下的人员
    handleNodeClick(data) {
      const aData = {
        isEnabled: true
      };
      this.loading = true;
      api_GET_OrganizationUnitsIdUsers(data.id, aData).then(res => {
        this.loading = false;
        this.checked = false;
        this.options = res.items;
        // 全选回显
        let idList = [];
        if (this.options.length > 0) {
          idList = this.options.map(item => {
            return item.id;
          });
        }
        const tf = this.includes(this.DraftCreateDto.targetIdList, idList);
        if (tf && this.options.length > 0) {
          this.checked = true;
        } else {
          this.checked = false;
        }
      }).catch(() => {
        this.loading = false;
      });
    }
  }
};
</script>

<style scoped>
.back {
  margin: 20px 2px;
}
.form {
  width: 90%;
}
.item {
  width: 100%;
}
.cascader {
  position: fixed;
  width: 100%;
  height: 100%;
  z-index: 6;
  background-color: transparent;
}
.option {
  height: auto;
}
.select_down {
  min-height: 100px;
  max-height: 200px;
}
.el-select /deep/ .el-select__tags {
  flex-wrap: unset;
  overflow: auto;
}
.el-select /deep/ .el-select__tags::-webkit-scrollbar {
  width: 3px;
  height: 3px;
}
.el-select /deep/ .el-select__tags::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background: rgb(24, 144, 255);
}
.el-select /deep/ .el-select__tags::-webkit-scrollbar-track {
  border-radius: 0;
  background: #ebeef5;
}
</style>
